//
//  PhotoFetching.m
//  OGL
//
//  Created by 洋 耿 on 15/4/8.
//  Copyright (c) 2015年 ZengYuan. All rights reserved.
//

#import "PhotoFetching.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "Config.h"
#import "LocalPhoto.h"
@implementation PhotoFetching
@synthesize delegate = _delegate;

static PhotoFetching* sharedPhotoFetcherInstance=nil;


//SINGLE TON MODE
+(PhotoFetching*)sharedPhotoFetcher
{
	@synchronized(self)
	{
		if (sharedPhotoFetcherInstance == nil) {
			sharedPhotoFetcherInstance = [[self alloc] init];
		}
	}
	return sharedPhotoFetcherInstance;
}

- (NSMutableArray *)photoUrlListArray{
    if (!_photoUrlListArray) {
        _photoUrlListArray = [NSMutableArray array];
    }
    
    return _photoUrlListArray;
}
//获取aiwebaby相册所有照片url
- (void)fetchphotosFromPhotoAlbum{
    if (self.photoUrlListArray.count > 0) {
        [self.photoUrlListArray removeAllObjects];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        
        ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror){
            if ([myerror.localizedDescription rangeOfString:@"Global denied access"].location!=NSNotFound) {
                
            }else{
                
            }
        };
        
        ALAssetsGroupEnumerationResultsBlock groupEnumerAtion = ^(ALAsset *result, NSUInteger index, BOOL *stop){
            if (result!=NULL) {
                
                //读取相册中照片
                if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
                    
                    LocalPhoto *photo = [[LocalPhoto alloc] init];
//                    photo.photoUrl = [NSString stringWithFormat:@"%@",[[result defaultRepresentation] url]];
                    
                    UIImage *orginImage = [UIImage imageWithCGImage:result.defaultRepresentation.fullScreenImage];
                    photo.originImage = orginImage;

                    UIImage *thumbimage = [UIImage imageWithCGImage:result.thumbnail];
                    photo.thumbnailImage = thumbimage;
                    photo.date = [result valueForProperty:ALAssetPropertyDate];

//                    [self.photoUrlListArray addObject:[[result defaultRepresentation] url]];
                    [self.photoUrlListArray addObject:photo];
                }
        
                }
            
        						   
            };
        
        ALAssetsLibraryGroupsEnumerationResultsBlock
        libraryGroupsEnumeration = ^(ALAssetsGroup* group,BOOL* stop){
            
            if (group!=nil) {
                
                NSString *name =[group valueForProperty:ALAssetsGroupPropertyName];
                NSLog(@"group name = %@", name);

                if ([name isEqualToString:ALBUMNAME]) {
                    
                    [group enumerateAssetsUsingBlock:groupEnumerAtion];
                    //代理通知获取的照片url数组
                    [self.delegate alubumLoadFinished:self.photoUrlListArray];
                }
            }
            
            
            
        };
        
        ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
        [library enumerateGroupsWithTypes:ALAssetsGroupAlbum
                               usingBlock:libraryGroupsEnumeration
                             failureBlock:failureblock];
        
    });
    

}

//根据相册照片url获取图片
-(void)fetchingPhotoWithUrl:(NSURL*)url
{
	//UIImage* image;
	ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];
	[assetsLibrary assetForURL:url 
				   resultBlock:^(ALAsset* myasset){
					   
					   ALAssetRepresentation* rep = [myasset defaultRepresentation];
					   
#if 0			//below is how to get the data which may be used for uploading by network.
					   Byte* buf = malloc([rep size]);
					   NSError* err = nil;					   
					   NSUInteger bytes = [rep getBytes:buf fromOffset:0LL
												 length:[rep size] error:&err];
					   if (err||bytes == 0) {
						   NSLog(@"eror bytes");
						   return;
					   }
					   NSData* data = [NSData dataWithBytesNoCopy:buf length:[rep size] 
													 freeWhenDone:YES];
					   
#endif					
					   
					   
					   //用代理返回获取的照片
					 UIImage*  image = [UIImage imageWithCGImage:[rep fullScreenImage]];
					   if (self.delegate !=nil && [self.delegate respondsToSelector:@selector(photoFetchingDidFinished:)]) {
						   [self.delegate photoFetchingDidFinished:image];
					  }
					   
					   
				   } failureBlock:^(NSError *err){
					   NSLog(@"error occours");
				   }];
	
}


-(NSMutableArray*)importPhotoUrls:(NSString*)archivePath
{
	if ([[NSFileManager defaultManager] fileExistsAtPath:archivePath])
	{
		NSData* photoUrlsData = [[NSData alloc] initWithContentsOfFile:archivePath];
		NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:photoUrlsData];
		
		NSMutableArray* photoUrlsDataArray = (NSMutableArray*)[unarchiver decodeObjectForKey:kDataKey];		
		return photoUrlsDataArray;
	}
	return nil;
}


//-(void)exportPhotoUrls:(NSMutableArray*)photos
//{
//	NSLog(@"exportPhotoUrls =%d", [photos count]);
//	NSString *archivePath = [NSTemporaryDirectory() stringByAppendingPathComponent:kFilename];
//	NSMutableData* eventData = [[NSMutableData alloc] init];
//	NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:eventData];
//	[archiver encodeObject:photos forKey:kDataKey];
//	[archiver finishEncoding];
//	[eventData writeToFile:archivePath atomically:YES];
//	NSLog(@"archivePath=%@",archivePath);
//	NSLog(@"data Length=%d", [eventData length]);
//	
//	UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"export" message:[NSString stringWithFormat:@"export %d items",[photos count]] 
//												   delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//	[alert show];
//}
@end
